#include "common.h"

/*** Client for echo-server ***/

typedef std::vector<Serializable*> prod_arr_t;

void init(prod_arr_t& products) {
    products.push_back(new A(2,3));
    products.push_back(new B(-1));
    products.push_back(new C(5.5));
}

void clear(prod_arr_t& products) {
    for (prod_arr_t::iterator it = products.begin(); it != products.end(); ++it)
        delete (*it);
}

int main() {
    int sockfd;
    struct sockaddr_in addr;
    char buf[BUF_SIZE];
    char message[BUF_SIZE];
    
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Error in socket creation");
        return errno;
    }

    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(MY_PORT);
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    
    if (connect(sockfd, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
        perror("Error in connection");
        close(sockfd);
        return errno;
    }
    
    prod_arr_t products;
    init(products);

    for (prod_arr_t::const_iterator it = products.begin(); it != products.end(); ++it)  {        
        std::cout << "send: " << (*it)->serialize() << std::endl;
        int send_result = send(sockfd, (*it)->serialize().c_str(), sizeof((*it)->serialize().c_str()), 0);
        if (send_result == -1 || send_result < sizeof((*it)->serialize().c_str())) {
            perror("Error in sending data");
            close(sockfd);
            return errno;        
        }
        int recv_result = recv(sockfd, buf, sizeof((*it)->serialize().c_str()), 0);
        if (recv_result == -1 || recv_result < sizeof((*it)->serialize().c_str())) {
            perror("Error in receiving data");
            close(sockfd);
            return errno;        
        }
        
        std::cout << "received: " << buf << std::endl;
    }

    clear(products);
    close(sockfd);
    return 0;
}
